package com.nexus.plugin.tenant;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Web层租户拦截器
 * 从请求头/参数中解析租户ID，设置到TenantContextHolder
 *
 * @Date 2025/7/25 11:18
 * @Author luzhengning
 **/
public class TenantInterceptor implements HandlerInterceptor {

    /**
     * 请求头中的租户ID标识（如：X-Tenant-Id）
     */
    private static final String TENANT_ID_HEADER = "X-Tenant-Id";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1. 从请求头获取租户ID（也可从参数、Cookie等获取）
        String tenantIdStr = request.getHeader(TENANT_ID_HEADER);

        // 2. 转换为Long并设置到上下文
        if (tenantIdStr != null && !tenantIdStr.isEmpty()) {
            try {
                Long tenantId = Long.parseLong(tenantIdStr);
                TenantContextHolder.setTenantId(tenantId);
            } catch (NumberFormatException e) {
                // 处理租户ID格式错误（如返回400错误）
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return false;
            }
        } else {
            // 处理租户ID缺失（如返回401/403错误）
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求结束后清除上下文，避免线程复用导致的租户ID污染
        TenantContextHolder.clear();
    }
}
